package com.ljx.itbbs.server.article.service.impl;

import com.ljx.itbbs.server.article.dao.ArticleTagDao;
import com.ljx.itbbs.server.article.domain.entity.ArticleTagEntity;
import com.ljx.itbbs.server.article.service.ArticleTagRelationService;
import com.ljx.itbbs.server.article.service.ArticleTagService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ArticleTagServiceImpl implements ArticleTagService {

    @Autowired
    private ArticleTagDao articleTagDao;

    @Lazy
    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private ArticleTagRelationService articleTagRelationService;

    @Override
    public void saveArticleTag(Long articleId, List<String> tagList) {
        // 保存文章标签并与文章相关联
        for (String tag : tagList) {
            // 查询标签是否存在
            ArticleTagEntity tagEntity = articleTagDao.getByContent(tag);
            // 不存在就保存
            if (Objects.isNull(tagEntity)){
                tagEntity = new ArticleTagEntity();
                tagEntity.setContent(tag);
                articleTagDao.save(tagEntity);
            }
            // 保存文章之间的关联
            articleTagRelationService.save(tagEntity.getId(), articleId);
        }
    }

    public void saveBatch(List<String> tagList){
        List<String> res = new ArrayList<>(tagList);
        List<String> articleTags = articleTagDao.getByContents(tagList)
                .stream()
                .map(ArticleTagEntity::getContent)
                .collect(Collectors.toList());
        res.removeAll(articleTags);
        articleTagDao.saveArticleTags(res);
    }

    @Override
    public void updateArticleTag(Long articleId, List<String> tagList) {
        // 先删除之前存在的标签
        articleTagRelationService.deleteArticleTagRelation(articleId);
        // 保存最新的
        articleTagService.saveArticleTag(articleId, tagList);
    }
}
